package com.shopping_back.controller;


import com.shopping_back.common.Result;
import com.shopping_back.pojo.dto.CartItemDTO;
import com.shopping_back.service.ICartItemService;
import com.shopping_back.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import com.shopping_back.pojo.dto.CartResponse;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 购物车商品表 前端控制器
 * </p>
 *
 * @author Jack
 * @since 2025-07-12
 */
@RestController
@RequestMapping("/api/cart-item")
@RequiredArgsConstructor
public class CartItemController {

    private final ICartItemService cartItemService;

    private final HttpServletRequest request; // 自动注入

    private final JwtUtils jwtUtils;

    @GetMapping("/get")
    public Result getCart(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam Long userId) {
        CartResponse cartResponse = cartItemService.getCartItems(userId, page, size);
        Map<String, Object> response = new HashMap<>();
        response.put("code", "200");
        response.put("data", cartResponse);
        response.put("message", null);
        return Result.success(cartItemService.getCartItems(userId, page, size));
    }

    @DeleteMapping("/delete")
    public Result removeCartItem(@RequestParam Long id) {
        cartItemService.removeCartItem(id);
        return Result.success("删除成功");
    }

    @PostMapping("/add")
    public Result addToCart(@RequestBody CartItemDTO dto) {
        // 从Token获取用户ID
        Long userId = jwtUtils.getCurrentUserId(request);
        dto.setUserId(userId);
        cartItemService.addToCart(dto);
        return Result.success("添加成功");
    }
}
